<?php
/*---------------------一、PHP文件引用----------------------------------*/
require_once 'response.php';
require_once 'connect_config.php';
require('../config.php');
require_once($CFG->libdir .'/enrollib.php');

/*---------------------二、变量参数定义-------------------------------*/
$courseid=$_GET['courseid'];
$token = $_GET['token'];
if(!$token)
{
	$coursename = $_POST['coursename'];
	$username = $_POST['username'];	
}
$status = false;
$msg = '';
$data = array();

//数据库连接
$conn = mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME,DB_PORT) or die('数据库连接失败');

//查询学生ID
if($token)
{
	$query1 = "select * from mdl_token where token = '$token'";
	$data1 = mysqli_query($conn, $query1);         
	$row1 = mysqli_fetch_array($data1);
	if($row1){
		$userid= $row1['user_id'];
	}else{
		$msg =	mysqli_errno($conn);
	}
}
else if($username)
{
	$query2 = "select * from mdl_user where username = '$username'";
	$data2 = mysqli_query($conn, $query2);         
	$row2 = mysqli_fetch_array($data2);
	if($row2){
		$userid= $row2['id'];
	}else{
		$msg =	mysqli_errno($conn);
	}
	$query3 = "select * from mdl_course where fullname = '$coursename'";
	$data3 = mysqli_query($conn, $query3);         
	$row3 = mysqli_fetch_array($data3);
	if($row3){
		$courseid= $row3['id'];
	}else{
		$msg =	mysqli_errno($conn);
	}
}

//选课
if($userid){
    $result=enrol_try_internal_enrol($courseid,$userid,5);
    $status=$result;
    $msg="success";
    echo Response::json($status,$msg,$data);
}else{
	$status = false;
	$msg = "login fail!";
	echo Response::json($status,$msg,$data);
}

?>